package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.constants.Constant;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author Yandel
 * @since 2025-05-16
 */
@Service
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {

//    private final IInteractionQuestionService questionService;
    private final InteractionQuestionMapper questionMapper;
    private final UserClient userClient;
    @Override
    public void addReplyOrCommons(ReplyDTO dto) {
/*        //1.获取用户id
        Long userId = UserContext.getUser();
        // 2.新增回答
        InteractionReply reply = BeanUtils.copyBean(dto, InteractionReply.class);
        reply.setUserId(userId);
        this.save(reply);
        // 3.累加评论数或者累加回答数
        //3.1.判断当前回复的类型是否是回答
        boolean isAnswer = dto.getAnswerId() == null; //true表示是回答
        if (!isAnswer) {
            //3.2.是评论，则需要更新上级回答的评论数量
            this.lambdaUpdate()
                    .eq(InteractionReply::getId, dto.getAnswerId())
                    .setSql("reply_times = reply_times + 1")
                    .update();

        }
        // 3.3.尝试更新问题表中的状态、 最近一次回答者的id、回答数量
        questionService.lambdaUpdate()
                .set(isAnswer, InteractionQuestion::getLatestAnswerId, reply.getAnswerId())
                //- 判断提交评论的用户是否是学生，如果是标记问题状态为未查看
                .set(dto.getIsStudent(), InteractionQuestion::getStatus, QuestionStatus.UN_CHECK.getValue())
                .setSql("answer_times = answer_times + 1")
                .eq(InteractionQuestion::getId, dto.getQuestionId());

     */

        // 获取当前登录用户的id
        Long userId = UserContext.getUser();

        // 保存回答或者评论 interaction_reply
        InteractionReply reply = BeanUtils.copyBean(dto, InteractionReply.class);
        reply.setUserId(userId);
        this.save(reply);


        InteractionQuestion question = questionMapper.selectById(reply.getQuestionId());
        // 判断是否是回答 dto.answerId 为空就是回答 不为空就是评论
        if (dto.getAnswerId() != null) {
            // 是评论 累加回答下的评论次数
            InteractionReply answerInfo = this.getById(dto.getAnswerId());
            answerInfo.setReplyTimes(answerInfo.getReplyTimes() + 1);
            this.updateById(answerInfo);
        } else {
            // 是回答 修改问题表最近一次回答id 同时累加问题表回答次数
            question.setLatestAnswerId(reply.getId());
            question.setAnswerTimes(question.getAnswerTimes() + 1);
        }
        // 判断是否是学生提交
        Boolean isStudent = dto.getIsStudent();
        if (isStudent) {
            // dto.isStudent为true 则代表学生提交 如果是则将问题表中该问题的status字段改为未查看
            question.setStatus(QuestionStatus.UN_CHECK);
        }
        questionMapper.updateById(question);


        //TODO 4.尝试累加积分 待做！

    }

    @Override
    public PageDTO<ReplyVO> queryReplyPage(ReplyPageQuery query, boolean forAdmin) {
        // 1.校验questionId和answerId是否都为空
        if (query.getQuestionId() == null && query.getAnswerId() == null) {
            throw new BadRequestException("问题id和回答id不能都为空");
        }
        // 2.分页查询interaction_reply表
        Page<InteractionReply> page = this.lambdaQuery()
                // 如果传问题id则拼接问题id条件
                .eq(query.getQuestionId() != null, InteractionReply::getQuestionId, query.getQuestionId())
                //.eq(query.getAnswerId() != null, InteractionReply::getAnswerId, query.getAnswerId())
                // 如果回答id没传，则查询answer_id为o的数据，也就是回答
                .eq(InteractionReply::getAnswerId, query.getAnswerId() == null ? 0L : query.getAnswerId())
                .eq(InteractionReply::getHidden, false)
                .page(query.toMpPage(// 先根据点赞数排序，点赞数相同，再按照创建时间排序
                        new OrderItem(Constant.DATA_FIELD_NAME_LIKED_TIME, false),
                        new OrderItem(Constant.DATA_FIELD_NAME_CREATE_TIME, true)));

        List<InteractionReply> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(0L, 0L);
        }
        // 3.补全其他数据
        Set<Long> uids = new HashSet<>();
        Set<Long> targetReplyIds = new HashSet<>();
        for (InteractionReply record : records) {
            if (!record.getAnonymity()) {
                uids.add(record.getUserId());
                uids.add(record.getTargetUserId());
            }
            if (record.getTargetReplyId() != null && record.getTargetReplyId() > 0) {
                targetReplyIds.add(record.getTargetReplyId());
            }
        }


        // 查询目标回复，如果目标回复不是匿名
        if (targetReplyIds.size() > 0) {
            List<InteractionReply> targetReplies = listByIds(targetReplyIds);
            Set<Long> targetUserIds = targetReplies.stream()
                    .filter(Predicate.not(InteractionReply::getAnonymity))
                    .map(InteractionReply::getUserId)
                    .collect(Collectors.toSet());
            uids.addAll(targetUserIds);
        }

        List<UserDTO> userDTOList = userClient.queryUserByIds(uids);
        Map<Long, UserDTO> userDTOMap = new HashMap<>();
        if (userDTOList != null) {
            userDTOMap = userDTOList.stream().collect(Collectors.toMap(UserDTO::getId, c -> c));
        }
        // 4.封装vo返回
        List<ReplyVO> voList = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO vo = BeanUtils.copyBean(record, ReplyVO.class);
            if (!record.getAnonymity()) {
                UserDTO userDTO = userDTOMap.get(record.getUserId());
                if (userDTO != null) {
                    vo.setUserName(userDTO.getName());
                    vo.setUserIcon(userDTO.getIcon());
                    vo.setUserType(userDTO.getType());
                }
            }
            UserDTO targetUserDTO = userDTOMap.get(record.getTargetReplyId());
            if (targetUserDTO != null) {
                vo.setTargetUserName(targetUserDTO.getName());
            }
            voList.add(vo);
        }
        return PageDTO.of(page, voList);
    }


    @Override
    public PageDTO<ReplyVO> queryReplyAdminPage(ReplyPageQuery query) {
        return queryReplyPage(query, true);
    }

    @Override
    public void hiddenReplyAdmin(Long id, Boolean hidden) {
        //1、校验id
        if (id == null) {
            throw new BadRequestException("id不能为空");
        }
        // 2、判断是评论还是回答
        InteractionReply reply = this.getById(id);
        if (reply == null) {
            throw new BadRequestException("回答数据不存在");
        }
        reply.setHidden(hidden);
        this.updateById(reply);

        int num =hidden ? -1 : 1;
        if (reply.getAnswerId()==0){//如果是0表示上级是回答
            //说明上级是评论
            InteractionReply interactionReply = this.lambdaQuery()
                    .eq(InteractionReply::getAnswerId, id)
                    .one();
            interactionReply.setReplyTimes(interactionReply.getReplyTimes()+num);
            return;
        }
        // 回答
        InteractionQuestion question = questionMapper.selectById(reply.getQuestionId());
        question.setAnswerTimes(question.getAnswerTimes()+num);
        questionMapper.updateById(question);
    }

    @Override
    public ReplyVO queryReplyAdminById(Long id) {
        //1、校验id
        if (id == null) {
            throw new BadRequestException("id不能为空");
        }
        InteractionReply reply = this.getById(id);
        if (reply == null) {
            throw new BadRequestException("回答数据不存在");
        }
        //拷贝基本属性
        ReplyVO vo = BeanUtils.copyBean(reply, ReplyVO.class);
        //设置用户信息——远程调用用户接口
        UserDTO userDTO = userClient.queryUserById(reply.getUserId());
        if (userDTO != null){
            vo.setUserName(userDTO.getName());
            vo.setUserIcon(userDTO.getIcon());
        }
        return vo;
    }
}

